<!--
	Copyright (C) 2010 Ethan Gruber
	Numishare: http://code.google.com/p/numishare/
	Apache License 2.0
	
	Heavily modified from upload form developed by Orbeon	
-->
<html xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:xforms="http://www.w3.org/2002/xforms" xmlns:ev="http://www.w3.org/2001/xml-events" xmlns:xs="http://www.w3.org/2001/XMLSchema"
	xmlns="http://www.w3.org/1999/xhtml" xmlns:xxforms="http://orbeon.org/oxf/xml/xforms" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:fr="http://orbeon.org/oxf/xml/form-runner"
	xmlns:datetime="http://exslt.org/dates-and-times" xmlns:xi="http://www.w3.org/2001/XInclude" xmlns:nuds="http://nomisma.org/nuds">
	<head>
		<title>Numishare: Upload CSV File</title>
		<!-- Core + Skin CSS -->
		<xhtml:link rel="stylesheet" type="text/css" href="/apps/numishare/css/jquery-ui-1.8.10.custom.css"/>
		<xhtml:link rel="stylesheet" href="/apps/numishare/css/reset-fonts-grids.css"/>
		<xhtml:link rel="stylesheet" href="/apps/numishare/css/base-min.css"/>
		<xhtml:link rel="stylesheet" href="/apps/numishare/css/fonts-min.css"/>

		<!-- numishare styling -->
		<xhtml:link rel="stylesheet" href="/apps/numishare/css/xforms.css"/>

		<xhtml:script type="text/javascript" src="/apps/numishare/javascript/jquery-1.6.1.min.js"/>
		<xhtml:script type="text/javascript" src="/apps/numishare/javascript/numishare-menu.js"/>
		<xforms:model>
			<!-- exist URL is stored in an XML file -->
			<xforms:instance id="exist-url">
				<xi:include href="exist-url.xml"/>
			</xforms:instance>
			
			<xforms:instance id="control-instance">
				<controls xmlns="">
					<simple-upload-trigger/>
					<add-upload-trigger/>
					<remove-upload-trigger/>
					<collection-name/>
				</controls>
			</xforms:instance>
			
			<xforms:instance id="dump">
				<dump/>
			</xforms:instance>
			
			<!-- collections/authentication instances -->
			<xforms:instance id="collections-list">
				<collections xmlns="">
					<collection roll="admin" name="numishare"/>
				</collections>
			</xforms:instance>

			<xforms:instance id="files-instance">
				<!-- Start with placeholders for three files -->
				<files xmlns="">
					<file xsi:type="xs:anyURI" filename="" mediatype="" size=""/>
				</files>
			</xforms:instance>

			<xforms:instance id="url-generator">
				<config xmlns="">
					<url/>
					<content-type>text/plain</content-type>
				</config>
			</xforms:instance>

			<xforms:instance id="xml-file">
				<root xmlns=""/>
			</xforms:instance>

			<xforms:instance id="row-template">
				<row xmlns=""/>
			</xforms:instance>

			<xforms:instance id="elem-template">
				<elem name="" mapping="" xmlns=""/>
			</xforms:instance>

			<xforms:instance id="processed-xml">
				<dsc xmlns=""/>
			</xforms:instance>

			<xforms:instance id="mapping">
				<mapping xmlns=""/>
			</xforms:instance>

			<xforms:instance id="mapping-column-template">
				<column xmlns="" label="" value=""/>
			</xforms:instance>

			<xforms:instance id="imports">
				<imports xmlns=""/>
			</xforms:instance>

			<xforms:instance id="import-template">
				<import xmlns="" date="" filename=""/>
			</xforms:instance>

			<xforms:instance id="file-template">
				<file id="" xmlns=""/>
			</xforms:instance>

			<xforms:instance id="fields">
				<fields xmlns="">
					<field label="Document ID" value="nudsid"/>
					<field label="Acknowledgment" value="acknowledgment"/>
					<field label="Acquisition: Acquired From" value="acquired-from"/>
					<field label="Acquisition: Acquired Date" value="acquired-date"/>
					<field label="Acquisition: Sale Catalog" value="sale-catalog"/>
					<field label="Acquisition: Sale Item" value="sale-item"/>
					<field label="Acquisition: Sale Price" value="sale-price"/>
					<field label="Appraisal Date" value="appraisal-date"/>
					<field label="Appraiser" value="appraiser"/>
					<field label="Artist" value="artist"/>
					<field label="Associated Object" value="associatedObject"/>
					<field label="Axis" value="axis"/>
					<field label="Authority: Personal" value="authority-personal"/>
					<field label="Authority: Personal URI" value="authority-personal-uri"/>
					<field label="Authority: Corporate" value="authority-corporate"/>
					<field label="Authority: Corporate URI" value="authority-corporate-uri"/>					
					<field label="Collection" value="collection"/>
					<field label="Commentary" value="description"/>
					<!--<field label="Color" value="color"/>-->
					<field label="Countermark: Description" value="countermark-description"/>
					<field label="Countermark: Obverse" value="countermark-obverse"/>
					<field label="Countermark: Reverse" value="countermark-reverse"/>
					<field label="Date on Object" value="dob"/>
					<field label="Date: From" value="fromDate"/>
					<field label="Date: To" value="toDate"/>
					<field label="Denomination" value="denomination"/>
					<field label="Denomination URI" value="denomination-uri"/>
					<field label="Department" value="department"/>
					<field label="Diameter" value="Diameter"/>
					<field label="Dynasty" value="famname"/>
					<field label="Edge Description" value="edge-description"/>
					<field label="Edge Legend" value="edge-legend"/>
					<field label="Edge Type" value="edge-type"/>
					<field label="Engraver" value="engraver"/>
					<field label="Height" value="height"/>
					<field label="Identifier" value="identifier"/>
					<field label="Image: Obverse Thumbnail" value="image-obverse-thumbnail"/>
					<field label="Image: Obverse Screen" value="image-obverse-reference"/>
					<field label="Image: Obverse Large" value="image-obverse-archive"/>
					<field label="Image: Reverse Thumbnail" value="image-reverse-thumbnail"/>
					<field label="Image: Reverse Screen" value="image-reverse-reference"/>
					<field label="Image: Reverse Large" value="image-reverse-archive"/>
					<field label="Issuer: Personal" value="issuer-personal"/>
					<field label="Issuer: Personal URI" value="issuer-personal-uri"/>
					<field label="Issuer: Corporate" value="issuer-corporate"/>
					<field label="Issuer: Corporate" value="issuer-corporate-uri"/>
					<field label="Maker: Personal" value="maker-personal"/>					
					<field label="Maker: Corporate" value="maker-corporate"/>					
					<field label="Magistrate" value="magistrate"/>
					<field label="Magistrate URI" value="magistrate-uri"/>
					<field label="Manufacture" value="manufacture"/>
					<field label="Material" value="material"/>
					<field label="Material URI" value="material-uri"/>
					<field label="Mint: Name" value="mint"/>
					<field label="Mint: URI" value="mint-uri"/>
					<field label="Object Type" value="objectType"/>
					<field label="Object Type URI" value="objectType-uri"/>
					<field label="Obverse Artist" value="obverse-artist"/>
					<field label="Obverse Completeness" value="obverse-completeness"/>
					<field label="Obverse Condition" value="obverse-condition"/>
					<field label="Obverse Deity" value="obverse-deity"/>
					<field label="Obverse Deity URI" value="obverse-deity-uri"/>					
					<field label="Obverse Engraver" value="obverse-engraver"/>
					<field label="Obverse Grade" value="obverse-grade"/>
					<field label="Obverse Legend" value="obverse-legend"/>
					<field label="Obverse Portrait" value="obverse-portrait"/>
					<field label="Obverse Portrait URI" value="obverse-portrait-uri"/>
					<field label="Obverse Symbol" value="obverse-symbol"/>
					<field label="Obverse Type" value="obverse-type"/>
					<field label="Obverse Wear" value="obverse-wear"/>
					<field label="Owner" value="owner"/>
					<field label="Physical Location" value="physloc"/>
					<field label="Previous Collection" value="prevcoll"/>
					<field label="Reference: Bibliographic Title" value="bibref-title"/>
					<field label="Reference: Bibliographic Number" value="bibref-num"/>
					<field label="Region: Name" value="region"/>
					<field label="Region: URI" value="region-uri"/>
					<field label="Repository" value="repository"/>
					<field label="Reverse Artist" value="reverse-artist"/>
					<field label="Reverse Completeness" value="reverse-completeness"/>
					<field label="Reverse Condition" value="reverse-condition"/>
					<field label="Reverse Deity" value="reverse-deity"/>
					<field label="Reverse Deity URI" value="reverse-deity-uri"/>
					<field label="Reverse Engraver" value="reverse-engraver"/>
					<field label="Reverse Grade" value="reverse-grade"/>
					<field label="Reverse Legend" value="reverse-legend"/>
					<field label="Reverse Portrait" value="reverse-portrait"/>
					<field label="Reverse Portrait URI" value="reverse-portrait-uri"/>
					<field label="Reverse Symbol" value="reverse-symbol"/>
					<field label="Reverse Type" value="reverse-type"/>
					<field label="Reverse Wear" value="reverse-wear"/>
					<!--<field label="Serial Number" value="sernum"/>
					<field label="Shape" value="shape"/>
					<field label="Signature" value="signature"/>-->
					<field label="Subject" value="subject"/>
					<field label="Thickness" value="thickness"/>
					<field label="Title" value="title"/>
					<field label="Typological Description URI" value="typeDesc-uri"/>
					<!--<field label="Watermark" value="watermark"/>-->
					<field label="Weight" value="weight"/>
					<field label="Width" value="width"/>
				</fields>
			</xforms:instance>

			<xforms:instance id="recordType-template">
				<recordType xmlns="">physical</recordType>
			</xforms:instance>

			<xforms:instance id="recordTypes">
				<recordTypes xmlns="">
					<recordType label="Physical" value="physical"/>
					<recordType label="Conceptual" value="conceptual"/>
				</recordTypes>
			</xforms:instance>


			<xforms:instance id="id-template">
				<id xmlns=""/>
			</xforms:instance>

			<xforms:instance id="current-id">
				<id xmlns=""/>
			</xforms:instance>

			<!--<xforms:instance id="publish">
				<publish xmlns=""/>
			</xforms:instance>-->

			<!-- send to Solr -->
			<xforms:instance id="addIndex">
				<add xmlns=""/>
			</xforms:instance>

			<!-- Instance for Solr commit-->
			<xforms:instance id="sendCommit">
				<commit/>
			</xforms:instance>

			<!-- Solr optimize -->
			<xforms:instance id="optimizeIndex">
				<optimize/>
			</xforms:instance>

			<xforms:instance id="status">
				<selected/>
			</xforms:instance>


			<!-- load URLs from config.xml in eXist into form for Solr and CSS file -->
			<xforms:instance id="config">
				<config xmlns=""/>
			</xforms:instance>

			<xforms:bind nodeset="instance('control-instance')">
				<xforms:bind nodeset="add-upload-trigger" readonly="false()"/>
				<xforms:bind nodeset="remove-upload-trigger" readonly="count(instance('files-instance')/file) le 1"/>
			</xforms:bind>

			<xforms:bind nodeset="instance('xml-file')">
				<xforms:bind nodeset="//row[last()]">
					<xforms:bind nodeset="recordType">
						<xforms:bind constraint="string-length(.) &gt; 0"/>
					</xforms:bind>
				</xforms:bind>
			</xforms:bind>
			
			<xforms:submission id="load-collections" serialization="none" method="get" action="{instance('exist-url')}collections-list.xml" replace="instance" instance="collections-list"
				xxforms:username="admin" xxforms:password="">
				<!-- if the config loads successfully, set the collection names based on authentication -->
				<xforms:action ev:event="xforms-submit-done">
					<!-- set default if security is false -->
					<xforms:action if="not(string(instance('control-instance')/request-security/role))">
						<xforms:setvalue ref="instance('control-instance')/collection-name">numishare</xforms:setvalue>
					</xforms:action>
					<!-- if there is a security role, set the collection-name value if it is in the list, otherwise set new collection name -->
					<xforms:action if="string(instance('control-instance')/request-security/role)">
						<xforms:action if="string(instance('collections-list')/collection[@role=instance('control-instance')/request-security/role]/@name)">
							<xforms:setvalue ref="instance('control-instance')/collection-name"
								value="instance('collections-list')/collection[@role=instance('control-instance')/request-security/role]/@name"/>
						</xforms:action>
					</xforms:action>			
					<xforms:send submission="load-imports"/>
					<xforms:send submission="load-config"/>
				</xforms:action>
				<!-- if the config has not been created (given that the URL in exist-url.xml is correct), create it -->
				<xforms:message ev:event="xforms-submit-error" level="modal">Unable to load Numishare collections list.</xforms:message>
			</xforms:submission>

			<!-- load site info -->
			<xforms:submission id="load-config" serialization="none" method="get" action="{instance('exist-url')}{instance('control-instance')/collection-name}/config.xml" xxforms:username="admin" xxforms:password="" replace="instance"
				instance="config"/>

			<xforms:submission id="background-submission" method="post" replace="none" resource="test:">
				<xforms:action ev:event="xforms-submit-done">
					<xforms:setvalue ref="instance('url-generator')/url" value="instance('files-instance')/file"/>
					<xforms:insert context="instance('xml-file')" origin="xxforms:call-xpl('oxf:/apps/numishare/xpl/convert-csv.xpl', 'file', instance('url-generator'), 'data')"/>
					<xforms:insert context="instance('xml-file')/root" nodeset="./child::node()[last()]" origin="instance('row-template')"/>
					<xforms:action xxforms:iterate="instance('xml-file')//row[1]/elem">
						<xxforms:variable name="name" select="@name"/>
						<xforms:setvalue context="instance('elem-template')" nodeset="@name" value="$name"/>
						<xforms:insert context="instance('xml-file')//row[last()]" nodeset="./child::node()[last()]" origin="instance('elem-template')"/>
					</xforms:action>
					<xforms:insert context="instance('xml-file')//row[last()]" origin="instance('recordType-template')"/>
					<xforms:toggle case="map-columns"/>
				</xforms:action>
			</xforms:submission>

			<xforms:submission id="save-submission" ref="instance('processed-xml')/*[local-name()='nuds'][*[local-name()='nudsHeader']/*[local-name()='nudsid'] = instance('current-id')]" xxforms:username="admin" xxforms:password=""
				action="{instance('exist-url')}{instance('control-instance')/collection-name}/objects/{instance('current-id')}.xml" method="put" replace="none">
				<xforms:message ev:event="xforms-submit-error" level="modal">Save Error!</xforms:message>
				<xforms:action ev:event="xforms-submit-done">
					<xforms:insert origin="instance('file-template')" context="instance('imports')/import[last()]" nodeset="./child::node()[last()]"/>
					<xforms:setvalue ref="instance('imports')/import[last()]/file[last()]/@id" value="instance('current-id')"/>
					<!--					<xforms:send submission="to-solr" if="instance('publish') = 'true'"/>-->
				</xforms:action>
				<!-- check to see if the document is already published to Solr -->
				<!--<xforms:send ev:event="xforms-submit-done" submission="query-solr-for-publication"/>-->
			</xforms:submission>

			<xforms:submission id="load-imports" serialization="none" method="get" action="{instance('exist-url')}{instance('control-instance')/collection-name}/imports.xml" xxforms:username="admin" xxforms:password="" replace="instance"
				instance="imports"/>

			<xforms:submission id="save-imports" ref="instance('imports')" xxforms:username="admin" xxforms:password="" action="{instance('exist-url')}{instance('control-instance')/collection-name}/imports.xml" method="put"
				replace="none">
				<xforms:action ev:event="xforms-submit-done">
					<xforms:send submission="submit-commit"/>
					<xforms:setvalue ref="instance('status')">CSV file succesfully imported.</xforms:setvalue>
				</xforms:action>
				<xforms:message ev:event="xforms-submit-error" level="modal">Error saving imports record.</xforms:message>
			</xforms:submission>

			<xforms:submission id="to-solr" method="get" replace="instance" instance="addIndex" serialization="none" resource="{instance('config')/url}id/{instance('current-id')}.solr">
				<xforms:message ev:event="xforms-submit-error" level="modal">Error transforming EAD guide to Solr document.</xforms:message>
				<xforms:send ev:event="xforms-submit-done" submission="publish-submission"/>
			</xforms:submission>
			<!-- post instance to Solr -->
			<xforms:submission id="publish-submission" action="{instance('config')/solr_published}update" ref="instance('addIndex')" instance="addIndex" replace="instance" method="post">
				<xforms:message ev:event="xforms-submit-error" level="modal">Data Failed to POST to Solr. Index may be offline or URL is incorrect.</xforms:message>
			</xforms:submission>
			<!-- send commit -->
			<xforms:submission id="submit-commit" action="{instance('config')/solr_published}update" ref="instance('sendCommit')" instance="sendCommit" replace="none" method="post">
				<xforms:send submission="optimize" ev:event="xforms-submit-done"/>
			</xforms:submission>

			<!-- send optimize -->
			<xforms:submission id="optimize" action="{instance('config')/solr_published}update" ref="instance('optimizeIndex')" instance="optimizeIndex" replace="none" method="post">
				<xforms:message ev:event="xforms-submit-error" level="modal">Failed to optimize Solr index.</xforms:message>
			</xforms:submission>

			<xforms:action ev:event="xforms-model-construct-done">
				<xforms:send submission="load-collections"/>
			</xforms:action>
		</xforms:model>
	</head>

	<xhtml:body class="yui-skin-sam">
		<xhtml:div id="doc4" class="yui-t2 content ui-corner-all">
			<xxforms:variable name="display_path">../../</xxforms:variable>
			<xi:include href="header.xml"/>
			<div id="bd">
				<xhtml:div id="form">
					<xforms:group ref="instance('status')/text()">
						<div class="success">
							<xforms:output ref="instance('status')"/>
						</div>
					</xforms:group>
					<xforms:switch>
						<xforms:case id="upload-file">
							<div class="section">
								<h3>Upload CSV file</h3>
								<p>Use this feature to import coins and medals into Numishare from a standard format CSV file.</p>
								<p>Please select the file to upload:</p>
								<xforms:group ref="instance('files-instance')/file">
									<div class="subsection">
										<!-- Upload field -->
										<fr:upload ref="." xxforms:size="60">
											<xforms:filename ref="@filename"/>
											<xforms:mediatype ref="@mediatype"/>
											<xxforms:size ref="@size"/>
										</fr:upload>
									</div>
								</xforms:group>
								<p>
									<xforms:submit submission="background-submission" ref="instance('control-instance')/simple-upload-trigger">
										<xforms:label>Upload</xforms:label>
									</xforms:submit>
								</p>
							</div>
						</xforms:case>
						<xforms:case id="map-columns">
							<xforms:group ref="instance('xml-file')//row[last()]">
								<div class="section">
									<h4>Map CSV columns to numismatic fields</h4>
									<p>Use the right column to select the semantically appropriate Numishare field to map to the CSV column heading, left.</p>
									<!-- list warnings -->
									<!--<xforms:group ref=".[count(elem[@mapping='title']) != 1]">
										<div class="ui-state-error ui-corner-all">
											<p><span class="ui-icon ui-icon-alert" style="float: left; margin-right: 0.3em;"/>
												<strong>Alert:</strong>Title must occur once.</p>
										</div>
									</xforms:group>-->
									<xforms:group ref=".[count(elem[@mapping='objectType']) != 1 and count(elem[@mapping='objectType-uri']) != 1]">
										<div class="ui-state-error ui-corner-all">
											<p><span class="ui-icon ui-icon-alert" style="float: left; margin-right: 0.3em;"/>
												<strong>Alert:</strong>Object Type must occur once.</p>
										</div>
									</xforms:group>
									<xforms:group ref=".[count(elem[@mapping='typeDesc-uri']) = 1]">
										<div class="ui-state-highlight ui-corner-all">
											<p><span class="ui-icon ui-icon-info" style="float: left; margin-right: 0.3em;"/>
												<strong>Note:</strong>When Typological Description URI is selected, other typological elements will be ignored.</p>
										</div>
									</xforms:group>
									<xforms:group ref=".[count(elem[@mapping='typeDesc-uri']) &gt; 1]">
										<div class="ui-state-error ui-corner-all">
											<p><span class="ui-icon ui-icon-alert" style="float: left; margin-right: 0.3em;"/>
												<strong>Alert:</strong>Typological Description URI may be selected at most one time.</p>
										</div>
									</xforms:group>
									<!--<div>
										<xforms:select ref="instance('publish')" appearance="full">
											<xforms:item>
												<xforms:label>Publish</xforms:label>
												<xforms:value>true</xforms:value>
											</xforms:item>
										</xforms:select>
									</div>-->
									<div>
										<xforms:select1 ref="recordType">
											<xforms:alert>Record Type is required.</xforms:alert>
											<xforms:label>Record Type</xforms:label>
											<xforms:itemset nodeset="instance('recordTypes')/recordType">
												<xforms:label ref="@label"/>
												<xforms:value ref="@value"/>
											</xforms:itemset>
										</xforms:select1>
									</div>
									<table>
										<thead>
											<tr>
												<th>CSV Column Label</th>
												<th>Numishare Field</th>
											</tr>
										</thead>
										<tbody>
											<xforms:repeat nodeset="elem">
												<tr>
													<td style="width:25%;">
														<xforms:output value="@name"/>
													</td>
													<td style="text-align:center;">
														<xforms:select1 ref="@mapping">
															<xforms:alert>Title cannot occur more than once.</xforms:alert>
															<xforms:item>
																<xforms:label>Select...</xforms:label>
																<xforms:value/>
															</xforms:item>
															<xforms:itemset nodeset="instance('fields')/field">
																<xforms:label ref="@label"/>
																<xforms:value ref="@value"/>
															</xforms:itemset>
														</xforms:select1>
													</td>
												</tr>
											</xforms:repeat>
										</tbody>
									</table>
									<!-- show import button only if it meets validation criteria -->
									<xforms:group ref=".[count(elem[@mapping='objectType']) = 1 or count(elem[@mapping='objectType-uri']) = 1]">
										<xforms:trigger>
											<xforms:label>Import</xforms:label>
											<xforms:action ev:event="DOMActivate">
												<xforms:action xxforms:iterate="instance('xml-file')//row[not(position() = last())]"
													if=".[count(instance('xml-file')//row[last()]/elem[@mapping='nudsid']) = 0 and count(id) = 0]">
													<xforms:insert context="." origin="instance('id-template')"/>
													<xforms:setvalue ref="id" value="concat('n_', substring(string(digest( string( random( true ) ), 'MD5', 'hex' )), 1, 8))"/>
												</xforms:action>
												<xforms:insert nodeset="instance('processed-xml')"
													origin="xxforms:call-xpl('oxf:/apps/numishare/xpl/xml-to-nuds.xpl', 'source', instance('xml-file'), 'finalized')"/>
												<!-- insert new import node -->
												<xforms:insert origin="instance('import-template')" context="instance('imports')" nodeset="./child::node()[last()]"/>
												<xforms:setvalue ref="instance('imports')/import[last()]/@date" value="concat(datetime:dateTime(), 'Z')"/>
												<xforms:setvalue ref="instance('imports')/import[last()]/@filename" value="instance('files-instance')/file/@filename"/>
												<!-- iterate through new components to save each one individually to eXist -->
												<xforms:action xxforms:iterate="instance('processed-xml')/*[local-name()='nuds']">
													<xforms:setvalue ref="instance('current-id')" value="context()/nuds:nudsHeader/nuds:nudsid"/>
													<xforms:send submission="save-submission"/>
												</xforms:action>
												<xforms:send submission="save-imports"/>
											</xforms:action>
										</xforms:trigger>
									</xforms:group>
								</div>
							</xforms:group>
						</xforms:case>
					</xforms:switch>
				</xhtml:div>
			</div>

			<!--<widget:xforms-instance-inspector id="orbeon-xforms-inspector" xmlns:widget="http://orbeon.org/oxf/xml/widget"/>-->

		</xhtml:div>
	</xhtml:body>
</html>
